package com.codeant.bikeindicatorapplication;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Button;
import com.allen.library.SuperButton;
import com.allen.library.SuperTextView;
import com.codeant.bikeindicatorapplication.tools.ClickFeedbackHelper;
import com.codeant.bikeindicatorapplication.tools.MyBroadcastReceiver;
import com.codeant.bikeindicatorapplication.tools.SharedPreferencesHelper;
import com.codeant.bikeindicatorapplication.tools.SingleToast;

public class SplashActivity extends Activity {

    private final int SPLASH_DISPLAY_LENGHT = 1000;   // ？秒后进入主页

    private SuperTextView app_name_stv;
    private SuperTextView ble_status_stv;
    private SuperTextView ss_status_stv;
    private SuperTextView app_version_stv;
    private Button go_sbtn;

    private ClickFeedbackHelper clickFeedbackHelper;

    public String READY_ON = "就绪（已打开）";
    public String READY_OFF = "就绪（未打开）";
    public String READY = "就绪";
    public String READY_NOT = "未就绪";
    public String STR_OK = "确定";

    public int BLE_STATUS = 0;//记录蓝牙硬件是否可用，0不可用，1可用
    public int BLE_SWITCH_STATUS = 0;//记录蓝牙状态否已打开，0未打开，1打开
    public int SS_STATUS = 0;//记录加速度传感器硬件是否可用，0不可用，1可用
    private int FLAG_BLE_RECEIVER = 0;//标记蓝牙接收器是否注册

    Boolean phone_status;//记录应用状态（据此决定首屏内容）

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //用来判断是否进入开屏页的数据记录工具需要单独创建
        SharedPreferencesHelper sph = new SharedPreferencesHelper();
        sph.initSP(SplashActivity.this);
        phone_status = sph.getSP_boolean("BI","phone_status",false);
        if (phone_status == true){
            setContentView(R.layout.activity_splash_logo);
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(getApplicationContext(),MainActivity.class);
                    startActivity(intent);
                    finish();
                }
            }, SPLASH_DISPLAY_LENGHT);//自动进入主页
        }else {
            setContentView(R.layout.activity_splash);

            initWidgets();//初始化控件

            initBle(SplashActivity.this);//初始化蓝牙情况

            //先设置按钮点击事件，后续再根据蓝牙状态决定是否禁用
            go_sbtn.setOnClickListener(v -> {
                //让所有可点击事件都带有震动反馈
                clickFeedbackHelper.feedback(v,SplashActivity.this);

                Intent mainIntent = new Intent(SplashActivity.this,
                        MainActivity.class);
                startActivity(mainIntent);
                finish();
            });

            //监听蓝牙状态的广播接收器
            IntentFilter bleStateFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
            this.registerReceiver(bleReceiver,bleStateFilter);
            FLAG_BLE_RECEIVER = 1;

            //先初始化一次按钮状态，有一个硬件不满足就禁止下一个功能，若蓝牙状态更改则通过广播接收器再次更改
            if(BLE_SWITCH_STATUS == 0 || SS_STATUS ==0){
                go_sbtn.setClickable(false);
                go_sbtn.setText(READY_NOT);
            }

        }

    }

    protected void onDestroy(){
        super.onDestroy();
        //若蓝牙广播接收器已被注册，则在MainActivity被关闭时要记得解绑它
        if (FLAG_BLE_RECEIVER == 1){
            this.unregisterReceiver(bleReceiver);
        }
    }

    // 初始化控件
    private void initWidgets(){
        app_name_stv = (SuperTextView) findViewById(R.id.app_name_stv_splash);
        ble_status_stv = (SuperTextView) findViewById(R.id.ble_status_stv_splash);
        ss_status_stv = (SuperTextView) findViewById(R.id.ss_status_stv_splash);
        app_version_stv = (SuperTextView) findViewById(R.id.app_version_stv_splash);
        go_sbtn = (SuperButton) findViewById(R.id.go_sbtn_splash);

        clickFeedbackHelper = new ClickFeedbackHelper();

        app_name_stv.setLeftTextIsBold(true);//标题加粗

        if(getSystemService(SENSOR_SERVICE) != null){
            ss_status_stv.setRightString(READY);
            SS_STATUS = 1;
        }
    }

    private void initBle(Context context){
        // 查看设备是否支持蓝牙
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter == null){
            SingleToast.getInstance(SplashActivity.this).show("此设备不支持蓝牙");
            ble_status_stv.setRightString(READY_NOT);
            BLE_STATUS = 0;//蓝牙不可用
            BLE_SWITCH_STATUS = 0;//由于蓝牙不可用，所以开关也禁用
        }else{
            SingleToast.getInstance(SplashActivity.this).show("此设备支持蓝牙");
            ble_status_stv.setRightString(READY_OFF);
            BLE_STATUS = 1;//蓝牙可用

            // 未打开蓝牙，请求打开蓝牙
            if(!mBluetoothAdapter.isEnabled()){
                SingleToast.getInstance(SplashActivity.this).show("未打开蓝牙，必须打开蓝牙使用本应用");
                ble_status_stv.setRightString(READY_OFF);
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivity(enableBtIntent);
            }else if(mBluetoothAdapter.isEnabled()){
                ble_status_stv.setRightString(READY_ON);
                BLE_SWITCH_STATUS = 1;//蓝牙已打开，开关可用
            }
            //只要设备支持蓝牙和加速度传感器（即开关可用），后续就不用再进入开屏页
            SharedPreferencesHelper sph = new SharedPreferencesHelper();
            sph.initSP(SplashActivity.this);
            sph.saveSP_boolean("BI","phone_status",true);
        }
    }


    //蓝牙状态的广播接收器
    public MyBroadcastReceiver bleReceiver = new MyBroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            super.onReceive(context, intent);

            String action = intent.getAction();
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            switch (action){
                case BluetoothDevice.ACTION_ACL_CONNECTED:
                    Log.i("Splash" , "蓝牙设备:" + device.getName() + "已连接" );
                    break;
                case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                    Log.i("Splash"  , "蓝牙设备:" + device.getName() + "断开连接" );
                    break;
                //上面的两个链接监听，其实也可以BluetoothAdapter实现，修改状态码即可
                case BluetoothAdapter.ACTION_STATE_CHANGED:
                    int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                    switch (blueState){
                        case BluetoothAdapter.STATE_OFF:
                            Log.i("Splash", "蓝牙关闭");
                            BLE_SWITCH_STATUS = 0;
                            go_sbtn.setClickable(false);
                            go_sbtn.setText(READY_NOT);
                            break;
                        case BluetoothAdapter.STATE_ON:
                            Log.i("Splash", "蓝牙开启");
                            BLE_SWITCH_STATUS = 1;
                            if(SS_STATUS == 1){
                                go_sbtn.setClickable(true);
                                go_sbtn.setText(READY);
                            }
                            break;
                    }
                    break;
                default:
                    break;
            }
        }
    };

}

